<template>
  <div>
    <transition name="el-fade-in-linear">
      <div :class="{'show':showEmoji}" class="emoji-container">
        <!-- 表情分类列表 -->
        <div class="emoji-list-container">
          <span class="emoji-item"
              v-for="(item, index) in emojiCategories"
              :key="item.text"
              @click="emojiIndex = index">
            <img class="emoji" :src="item.url" :title="item.text" width="36px" height="36px"/>
          </span>
        </div>
        <!-- 当前分类的表情 -->
        <div class="emoji-item-container">
          <span v-if="currentEmotes.length === 0" class="empty-emotes">暂无表情</span>
          <span class="emoji-item"
                v-for="(item, index) in currentEmotes"
                :key="currentCategory + index"
                @click="addEmoji(item.text)">
            <div v-if="item.url && item.url.indexOf('http') === -1" class="emoji">{{item.text}}</div>
            <img v-else class="emoji" :src="item.url" :title="item.text" width="36px" height="36px"/>
          </span>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useMainStore } from '../../store'

const props = defineProps({
  showEmoji: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['addEmoji'])

// 使用Pinia store
const store = useMainStore()
const emojiIndex = ref(0)
const emojiCategories = ref([])
const emojiData = ref([])
const isLoading = ref(false)

// 确保在显示表情时加载数据
watch(() => props.showEmoji, async (newVal) => {
  if (newVal && !isLoading.value) {
    isLoading.value = true
    await loadEmojiData()
    isLoading.value = false
  }
})

// 计算当前选中的表情类别
const currentCategory = computed(() => emojiCategories.value[emojiIndex.value]?.text || '')
const currentEmotes = computed(() => {
  if (!currentCategory.value || emojiData.value.length === 0) return []
  
  // 查找当前分类的所有表情
  const category = emojiData.value.find(cat => cat.text === currentCategory.value)
  return category?.emote || []
})

// 加载表情数据
async function loadEmojiData() {
  try {
    // 直接从localStorage获取数据，这样可以包含网络加载的表情
    const storedData = localStorage.getItem('emoji')
    if (storedData) {
      try {
        const parsedData = JSON.parse(storedData)
        if (Array.isArray(parsedData)) {
          emojiData.value = parsedData
          // 提取分类列表
          emojiCategories.value = parsedData.map(category => ({
            text: category.text,
            url: category.url
          }))
          console.log('从localStorage加载了', emojiData.value.length, '个表情分类')
          return
        }
      } catch (e) {
        console.error('解析localStorage中的emoji数据失败:', e)
      }
    }
    
    // 如果localStorage没有或解析失败，从store加载
    if (!store.hasEmojiLoaded) {
      // 先尝试从localStorage加载
      const loaded = store.loadStoredEmojiData()
      if (!loaded) {
        // 如果没有，则从本地JSON加载
        await store.loadLocalEmojiData()
      }
    }
    
    // 等待数据加载完成后，从localStorage再次获取最新数据
    const refreshedData = localStorage.getItem('emoji')
    if (refreshedData) {
      emojiData.value = JSON.parse(refreshedData)
      emojiCategories.value = emojiData.value.map(category => ({
        text: category.text,
        url: category.url
      }))
      console.log('从store加载了', emojiData.value.length, '个表情分类')
    }
  } catch (error) {
    console.error('加载emoji数据失败:', error)
  }
}

onMounted(async () => {
  await loadEmojiData()
})

// 添加表情的方法
const addEmoji = (text) => {
  emit('addEmoji', text)
}
</script>

<style scoped>
  .emoji-container{
    user-select: none;
    width: 100%;
    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
    transition: .3s;
    background: var(--background);
    box-shadow: 1px 1px 5px var(--themeBackground);
  }
  .emoji-container.show {
    height: unset;
    max-height: 380px;
    opacity: 1;
  }
  .emoji-item-container{
    width: 100%;
    max-height: 160px;
    overflow-y: scroll;
    padding: 5px 0;
    min-height: 50px;
  }
  .empty-emotes {
    display: block;
    text-align: center;
    color: #999;
    padding: 15px 0;
  }
  .emoji-item {
    cursor: pointer;
    display: inline-block;
  }
  .emoji-list-container{
    background: var(--maxLightGray);
    padding: 5px 0;
  }
  .emoji-item:hover {
    transition: all 0.2s;
    border-radius: 0.25rem;
    background: var(--lightGray);
  }
  .emoji {
    margin: 0.25rem;
    /* 把此元素放置在父元素的中部 */
    vertical-align: middle;
  }
  div.emoji{
    font-size: 16px;
    font-weight: 100;
    margin: 8px;
  }
  .body-enter-active, .body-leave-active {
    transition: all 0.3s;
  }

  .body-enter, .body-leave-to {
    opacity: 0;
  }
</style>
